package com.order.frontend.order.service;

import com.alibaba.fastjson.JSON;
import com.order.frontend.order.Entity.Message.Messages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class PrivateChatRedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 存储1对1聊天消息
     * 使用Sorted Set按时间排序
     */
    public void savePrivateMessage(Messages message) {

        String chatKey = getChatKey(message.getSenderId(), message.getReceiverId());
        double timestamp = message.getTimestamp() != null ?
                message.getTimestamp() :
                System.currentTimeMillis();

        // 序列化消息
        String messageJson = JSON.toJSONString(message);
        redisTemplate.opsForZSet().add(chatKey, messageJson, timestamp);

        // 限制消息数量，防止内存溢出
        redisTemplate.opsForZSet().removeRange(chatKey, 0, -1000); // 保留最近1000条消息

        // 为接收者设置未读消息计数
        if (!isUserOnline(message.getReceiverId())) {
            redisTemplate.opsForValue().increment("user:unread:" + message.getReceiverId(), 1);
        }
    }

    /**
     * 获取聊天历史消息
     */
    public List<Messages> getChatHistory(String user1Id, String user2Id, int count) {
        String chatKey = getChatKey(user1Id, user2Id);

        // 获取最新的count条消息
        Set<Object> messages = redisTemplate.opsForZSet()
                .reverseRange(chatKey, 0, count - 1);

        return messages.stream()
                .map(msg -> JSON.parseObject((String)msg, Messages.class))
                .collect(Collectors.toList());
    }

    /**
     * 获取未读消息数
     */
    public Long getUnreadCount(String userId) {
        String unreadKey = "user:unread:" + userId;
        Object count = redisTemplate.opsForValue().get(unreadKey);
        return count == null ? 0L : Long.valueOf(count.toString());
    }

     /**
     * 清除未读消息计数
     */
    public void clearUnreadCount(String userId) {
        redisTemplate.opsForValue().set("user:unread:" + userId, 0);
    }

    /**
     * 用户在线状态管理
     */
    public void setUserOnline(String userId) {
        redisTemplate.opsForValue().set("user:online:" + userId, "1", 30, TimeUnit.MINUTES);
    }

    public boolean isUserOnline(String userId) {
        return redisTemplate.hasKey("user:online:" + userId);
    }

    /**
     * 生成聊天key（保证两个用户之间的key一致）
     */
    private String getChatKey(String user1Id, String user2Id) {
        // 按用户ID排序，保证两个用户看到的是同一个聊天记录
        String[] users = {user1Id, user2Id};
        Arrays.sort(users);
        return "chat:private:" + users[0] + ":" + users[1];
    }
}

